var spawn = require('child_process').spawn;
var exec = require('child_process').exec;
var path = require("path");
var fs = require("fs");

function Node_PHP(opts) {
	opts || (opts = {});
	this.includes = [];
	this.commands = [];
	this.args_map = {};
	this.is_debug = opts.debug;
	this._start_placeholder = "（" + Math.random().toString(16).substr(2) + "））";
	this.start_placeholder = JSON.stringify(this._start_placeholder);
	this._end_placeholder = "（（" + Math.random().toString(16).substr(2) + "）";
	this.end_placeholder = JSON.stringify(this._end_placeholder);
	this._var_placeholder = "（—" + Math.random().toString(16).substr(2) + "）";
	this.var_placeholder = JSON.stringify(this._var_placeholder);
};
//将字符串转为命令行中的字符串变量
Node_PHP.str2com = function(str) {
	return JSON.stringify(JSON.stringify(str))
};
Node_PHP.prototype = {
	debug: function(type, args) {
		if (!args) {
			args = type;
			type = "log";
		}
		if (!(args instanceof Array)) {
			args = [args];
		}
		this.is_debug && console[type].apply(console, args);
	},
	include: function(file_name) {
		this.includes.push(path.resolve(file_name));
		return this;
	},
	clear: function() {
		this.includes.length = 0;
		this.commands.length = 0;
		return this;
	},
	//获取参数
	get: function(arg_name, return_var) {
		if (!return_var) {
			throw "返回参数名不可为空";
		}
		var command_str = "echo " + this.start_placeholder + "," + JSON.stringify(return_var) + "," + this.var_placeholder + ",json_encode(" + arg_name + ")," + this.end_placeholder;
		this.commands.push(command_str);
		return this;
	},
	//添加php语句
	add: function(command_str) {
		this.commands.push(command_str);
		return this;
	},
	//运行并获取返回值
	get_fun: function(fun_name, args, return_var) {
		if (!return_var) {
			throw "返回参数名不可为空";
		}
		var command_str = "echo " + this.start_placeholder + "," + JSON.stringify(return_var) + "," + this.var_placeholder + ",json_encode(" +
			fun_name + "(" + args.map(function(arg) {
				return "json_decode(" + Node_PHP.str2com(arg) + ")";
			}).join(",") + ")" +
			")," + this.end_placeholder;
		this.commands.push(command_str);
		return this;
	},
	//直接运行命令，并不获取返回值
	fun: function(fun_name, args) {
		var command_str = fun_name + "(" + args.map(function(arg) {
			return "json_decode(" + Node_PHP.str2com(arg) + ")";
		}).join(",") + ")";
		this.commands.push(command_str);
		return this;
	},
	//结束php语句制造，运行php语句
	end: function(cb) {
		var self = this;
		var includes_str = this.includes.map(function(file_name) {
			return "include_once(" + JSON.stringify(file_name) + ")";
		}).join(";\n");
		var command_str = this.commands.join(";\n");
		var spawn_command_str = "<?php\n" + includes_str + ";\n" + command_str + ";\n?>";
		self.debug(JSON.stringify(spawn_command_str));
		var result_buffs = [];
		var php_file_name = Math.random().toString(16).substr(1) + ".php";
		var php_file_path = path.resolve(__dirname, php_file_name);
		console.log(php_file_path);
		fs.writeFileSync(php_file_path, spawn_command_str);

		var _php = exec("php " + php_file_path, function(error, stdout, stderr) {
			if (error) {
				console.error(error);
			}
			stdout && self.debug("OK: " + stdout);
			stderr && self.debug("ER: " + stderr);
			cb && cb(stdout);
		});
		return this;
	},
};

/*test*/
// new Node_PHP({
// 		// debug: true
// 	})
// 	// .fun("echo", ["Hello World"])
// 	// .end(function(output) {
// 	// 	console.log("----TEST 1----");
// 	// 	console.log(output);
// 	// })
// 	// .clear()
// 	.include(__dirname + "/../wx/WxPayPubHelper/WxPayPubHelper.php")
// 	.add("$unifiedOrder = new UnifiedOrder_pub()")
// 	.add('$unifiedOrder->setParameter("openid","------------openid----------");')
// 	.add('$unifiedOrder->setParameter("body","贡献一分钱");')
// 	.add("$timeStamp = time()")
// 	.add('$out_trade_no = WxPayConf_pub::APPID."$timeStamp"')
// 	.add('$unifiedOrder->setParameter("out_trade_no","$out_trade_no");')
// 	.add('$unifiedOrder->setParameter("total_fee","1");')
// 	.add('$unifiedOrder->setParameter("spbill_create_ip","192.168.0.1");')
// 	.add('$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);')
// 	.add('$unifiedOrder->setParameter("trade_type","JSAPI");')
// 	// .get_fun("$unifiedOrder->createXml", [], "hehe")
// 	.add("echo $unifiedOrder->getPrepayId()")
// 	.end(function(output) {
// 		console.log("----TEST 2----");
// 		console.log(output);
// 	});

module.exports = Node_PHP;